package com.zkld.controller;

import com.github.pagehelper.PageInfo;
import com.zkld.pojo.User;
import com.zkld.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/all")
    public String home(Model model,@RequestParam(defaultValue = "1",required = false) Integer p){
        //System.out.println("------------" + p);
        PageInfo<User> pageInfo = userService.queryAllByPage(p);
        model.addAttribute("list",pageInfo);
        return "user/home";
    }

    @GetMapping("/add")
    public String add(){
        return "user/add";
    }

    @PostMapping("/add")
    public String add(Model model, User user){
        String errorMessage = "";
        User user1 = userService.queryByMobile(user.getMobile());
        if (user1 != null){
            errorMessage = "mobile already exit!";
            model.addAttribute("errorMessage",errorMessage);
            model.addAttribute("user",user);
            return "user/add";
        }else {
            userService.addUser(user);
            return "redirect:/user/all";
        }
    }

    @GetMapping("/{id}")
    public String details(@PathVariable("id") String id,Model model){
        User user = userService.queryById(id);
        model.addAttribute("user",user);
        return "user/details";
    }

    @GetMapping("/update/{id}")
    public String update(@PathVariable("id")Integer id,Model model){
        model.addAttribute("user",userService.queryById(String.valueOf(id)));
        return "user/update";
    }

    @PostMapping("/update")
    public String updateUser(User user,Model model,@RequestParam("oldPassword")String oldPassword){
        String res = userService.update(user,oldPassword);
        if (!StringUtils.isEmpty(res)){
            model.addAttribute("errorMessage",res);
            model.addAttribute("user",user);
            return "user/update";
        }
        Thread thread = new Thread();
        thread.start();
        return "redirect:/user/all";
    }

}
